package com.seguriapp.complaints.gwt.server;

import java.util.Calendar;

import net.customware.gwt.dispatch.server.ExecutionContext;
import net.customware.gwt.dispatch.shared.DispatchException;
import net.sf.json.JSONException;
import net.sf.json.JSONObject;

import org.apache.log4j.Logger;
import org.restlet.resource.ClientResource;

import com.seguriapp.common.config.GlobalConfigLoader;
import com.seguriapp.common.gwt.server.AbstractSeguriAppHandler;
import com.seguriapp.complaints.gwt.shared.SaveComplaintDataAction;
import com.seguriapp.complaints.gwt.shared.SaveComplaintDataResult;
import com.seguriapp.entities.Complaint;
import com.seguriapp.util.Util;

public class SaveComplaintDataHandler extends AbstractSeguriAppHandler<SaveComplaintDataAction, SaveComplaintDataResult> {

  private static final Logger LOGGER = Logger.getLogger(SaveComplaintDataHandler.class);

  public Class<SaveComplaintDataAction> getActionType() {
    return SaveComplaintDataAction.class;
  }

  public SaveComplaintDataResult execute(final SaveComplaintDataAction action, final ExecutionContext context) throws DispatchException {

    final SaveComplaintDataResult result = new SaveComplaintDataResult();
    try {
      final String url = GlobalConfigLoader.getInstance().getGlobalConfig().getBackEndUrl()
          .concat(GlobalConfigLoader.getInstance().getGlobalConfig().getSaveComplaint());
      final ClientResource resource = new ClientResource(url);
      final String complaintListStr = resource.post(convertDataToJsonString(action)).getText();
      LOGGER.info("Data received : \n" + complaintListStr);
      result.setComplaintId(getComplaintIdFromString(complaintListStr));
    } catch (Exception e) {
      LOGGER.error("Error al registrar denuncia", e);
    }
    return result;
  }

  private String convertDataToJsonString(final SaveComplaintDataAction action) {
    final JSONObject obj = new JSONObject();
    final Complaint complaint = action.getComplaint();
    try {
      obj.put("names", complaint.getNames());
      obj.put("lastNames", complaint.getLastNames());
      obj.put("dni", complaint.getDni());
      obj.put("address", complaint.getAddress());
      obj.put("email", complaint.getEmail());
      obj.put("phone", complaint.getPhone());
      obj.put("complaintlongitude", complaint.getComplaintLongitude());
      obj.put("complaintlatitude", complaint.getComplaintLatitude());
      obj.put("crimelatitude", complaint.getCrimeLatitude());
      obj.put("crimelongitude", complaint.getCrimeLongitude());
      obj.put("description", complaint.getDescription());
      obj.put("categoryId", complaint.getCategory().getId());
      obj.put("entityId", complaint.getPoliceStation().getId());
      obj.put("deviceId", GlobalConfigLoader.getInstance().getGlobalConfig().getDeviceId());

      // set date and time
      final Calendar calendar = Calendar.getInstance();
      calendar.setTime(complaint.getCrimeDate());
      calendar.add(Calendar.MINUTE, complaint.getMinute());
      calendar.add(Calendar.HOUR_OF_DAY, complaint.getHour());

      obj.put("crimeDate", Util.parseDateToString(calendar.getTime()));
    } catch (JSONException e) {
      LOGGER.error("Error al convertir parametros de busqueda a json", e);
    }
    LOGGER.info("Sending Data : \n" + obj.toString());
    return obj.toString();
  }

  private Long getComplaintIdFromString(final String complaintListStr) {
    if (complaintListStr != "false") {
      return Long.valueOf(complaintListStr);
    }
    return null;
  }

}
